package models;

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

import javax.imageio.ImageIO;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;

import play.data.validation.Constraints;
import play.db.ebean.Model;

/*
 * Image model class.
 * Stores binary data of an image
 * and binary data of thumbnail.
 * Author: Khalmuratov Alisher
 */

@Entity
public class Image extends Model {
	@Id
	public Long id;
	
	@Lob
	public byte[] image;
	
	@Lob
	public byte[] thumb;
	
	public String title;
	
	public String type;
	
	public String size = "0";
	
	@Constraints.Required
	public String res = "0";
	
	@ManyToOne(cascade = CascadeType.PERSIST)
	public Product product;
	
	public static Finder<Long, Image> find = new Finder<Long, Image>(Long.class, Image.class);
	
	public static Image create(byte[] image, String title, String type)
	{
		Image img = new Image();
		img.image = image;
		img.title = title;
		img.type = type;
		try{
			BufferedImage bi = ImageIO.read(new ByteArrayInputStream(image));
			img.res = bi.getWidth()+" "+bi.getHeight();
			img.size = image.length/1000+"kb";
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			BufferedImage thumb = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
			thumb.createGraphics().drawImage(bi.getScaledInstance(100, 100, BufferedImage.SCALE_SMOOTH),0,0,null);
			ImageIO.write(thumb, img.type.replace("image/",""), baos);
			img.thumb = baos.toByteArray();
			System.out.println(img.size);
		}catch(IOException e){}
		return img;
	}
	
	public static Image getImage(Long id)
	{
		return find.where().eq("id", id).findUnique();
	}
	
	public static List<Image> getImages()
	{
		return find.all();
	}
}
